package com.lagou.edu.users.service.impl;

import com.lagou.edu.users.mapper.LagouTokenMapper;
import com.lagou.edu.users.mapper.LagouUserMapper;
import com.lagou.edu.users.pojo.LagouToken;
import com.lagou.edu.users.pojo.LagouUser;
import com.lagou.edu.users.service.LagouUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.UUID;

@Service
public class LagouUserServiceImpl implements LagouUserService {

    @Autowired
    private LagouUserMapper lagouUserMapper;

    @Autowired
    private LagouTokenMapper lagouTokenMapper;

    @Override
    public LagouUser saveUser(LagouUser user) {
        if (user.getId() == null){
            lagouUserMapper.insert(user);
        }else {
            lagouUserMapper.updateByPrimaryKey(user);
        }
        return user;
    }

    @Override
    public LagouUser getUserById(Long id) {
        return lagouUserMapper.selectByPrimaryKey(id);
    }

    @Override
    public LagouUser getLagouUserByEmail(String email) {
        LagouUser lagouUser = new LagouUser();
        lagouUser.setEmail(email);
        LagouUser lagouUser1 = lagouUserMapper.selectOne(lagouUser);
        return lagouUser1;
    }

    @Override
    public Integer getCheckEmail(String email) {
        LagouUser lagouUser = new LagouUser();
        lagouUser.setEmail(email);
        int selectCount = lagouUserMapper.selectCount(lagouUser);
        return selectCount;
    }



    @Override
    public void saveToken(LagouToken token) {
        if (token.getId() == null){
            lagouTokenMapper.insert(token);
        }else {
            lagouTokenMapper.updateByPrimaryKey(token);
        }
    }

    @Override
    public String generateToken(String email, String password) {
        return UUID.randomUUID().toString();
    }

    @Override
    public LagouToken getTokenByToken(String token) {
        Example example = new Example(LagouToken.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("token",token);
        LagouToken lagouToken = lagouTokenMapper.selectOneByExample(example);
        return lagouToken;
    }

    @Override
    public LagouToken getTokenByEmail(String email) {
        Example example = new Example(LagouToken.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("email",email);
        LagouToken lagouToken = lagouTokenMapper.selectOneByExample(example);
        return lagouToken;
    }

}
